package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.common.Result;
import com.zhentao.dto.NotificationQueryRequest;
import com.zhentao.pojo.SystemNotification;
import com.zhentao.pojo.UserNotificationRead;
import com.zhentao.service.SystemNotificationService;
import com.zhentao.service.UserNotificationReadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 消息通知控制器
 */
@RestController
@RequestMapping("/api/notification")
@CrossOrigin
public class NotificationController {

    @Autowired
    private SystemNotificationService systemNotificationService;
    
    @Autowired
    private UserNotificationReadService userNotificationReadService;

    /**
     * 获取用户通知列表
     */
    @PostMapping("/list")
    public Result<Map<String, Object>> getNotifications(@RequestBody NotificationQueryRequest request,
                                                       @RequestParam Long userId) {
        try {
            // 创建分页对象
            Page<SystemNotification> page = new Page<>(request.getPageNum(), request.getPageSize());
            
            // 构建查询条件
            QueryWrapper<SystemNotification> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", "ACTIVE"); // 只查询激活状态的通知
            
            // 过滤过期通知
            queryWrapper.and(wrapper -> wrapper
                .isNull("expire_time")
                .or().gt("expire_time", new Date())
            );
            
            // 按通知类型过滤
            if (StringUtils.hasText(request.getType())) {
                queryWrapper.eq("type", request.getType());
            }
            
            // 按目标用户过滤
            queryWrapper.and(wrapper -> wrapper
                .eq("target_type", "ALL")
                .or().eq("target_type", "USER").like("target_value", userId.toString())
                .or().eq("target_type", "ROLE") // 这里可以根据用户角色进一步过滤
            );
            
            // 按优先级和发布时间排序
            queryWrapper.orderByDesc("priority").orderByDesc("publish_time");
            
            // 执行分页查询
            IPage<SystemNotification> result = systemNotificationService.page(page, queryWrapper);
            
            // 获取用户的阅读记录
            List<Long> notificationIds = result.getRecords().stream()
                .map(SystemNotification::getId)
                .collect(Collectors.toList());
            
            Map<Long, Boolean> readStatusMap = new HashMap<>();
            if (!notificationIds.isEmpty()) {
                QueryWrapper<UserNotificationRead> readWrapper = new QueryWrapper<>();
                readWrapper.eq("user_id", userId);
                readWrapper.in("notification_id", notificationIds);
                
                List<UserNotificationRead> readRecords = userNotificationReadService.list(readWrapper);
                readRecords.forEach(record -> 
                    readStatusMap.put(record.getNotificationId(), record.getIsRead() == 1)
                );
            }
            
            // 如果只查询未读消息，过滤已读消息
            if (request.getUnreadOnly() != null && request.getUnreadOnly()) {
                List<SystemNotification> unreadNotifications = result.getRecords().stream()
                    .filter(notification -> !readStatusMap.getOrDefault(notification.getId(), false))
                    .collect(Collectors.toList());
                result.setRecords(unreadNotifications);
                result.setTotal(unreadNotifications.size());
            }
            
            // 为每个通知添加阅读状态
            result.getRecords().forEach(notification -> {
                // 这里可以通过扩展字段或者Map来添加阅读状态
                // 暂时通过注释说明，实际使用时可以创建VO类
            });
            
            // 构建返回结果
            Map<String, Object> data = new HashMap<>();
            data.put("records", result.getRecords());
            data.put("total", result.getTotal());
            data.put("current", result.getCurrent());
            data.put("size", result.getSize());
            data.put("pages", result.getPages());
            data.put("readStatus", readStatusMap);
            
            return Result.success("查询成功", data);
            
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 获取未读消息数量
     */
    @GetMapping("/unread-count")
    public Result<Integer> getUnreadCount(@RequestParam Long userId) {
        try {
            // 获取用户可见的所有通知
            QueryWrapper<SystemNotification> notificationWrapper = new QueryWrapper<>();
            notificationWrapper.eq("status", "ACTIVE");
            notificationWrapper.and(wrapper -> wrapper
                .isNull("expire_time")
                .or().gt("expire_time", new Date())
            );
            notificationWrapper.and(wrapper -> wrapper
                .eq("target_type", "ALL")
                .or().eq("target_type", "USER").like("target_value", userId.toString())
                .or().eq("target_type", "ROLE")
            );
            
            List<SystemNotification> allNotifications = systemNotificationService.list(notificationWrapper);
            
            if (allNotifications.isEmpty()) {
                return Result.success("查询成功", 0);
            }
            
            // 获取用户已读的通知ID列表
            QueryWrapper<UserNotificationRead> readWrapper = new QueryWrapper<>();
            readWrapper.eq("user_id", userId);
            readWrapper.eq("is_read", 1);
            readWrapper.in("notification_id", 
                allNotifications.stream().map(SystemNotification::getId).collect(Collectors.toList())
            );
            
            List<UserNotificationRead> readRecords = userNotificationReadService.list(readWrapper);
            List<Long> readNotificationIds = readRecords.stream()
                .map(UserNotificationRead::getNotificationId)
                .collect(Collectors.toList());
            
            // 计算未读数量
            int unreadCount = (int) allNotifications.stream()
                .filter(notification -> !readNotificationIds.contains(notification.getId()))
                .count();
            
            return Result.success("查询成功", unreadCount);
            
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 标记消息为已读
     */
    @PostMapping("/mark-read")
    public Result<String> markAsRead(@RequestParam Long notificationId, 
                                   @RequestParam Long userId) {
        try {
            // 检查通知是否存在
            SystemNotification notification = systemNotificationService.getById(notificationId);
            if (notification == null) {
                return Result.notFound("通知不存在");
            }
            
            // 检查是否已有阅读记录
            QueryWrapper<UserNotificationRead> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("notification_id", notificationId);
            queryWrapper.eq("user_id", userId);
            
            UserNotificationRead existingRecord = userNotificationReadService.getOne(queryWrapper);
            
            if (existingRecord != null) {
                // 更新现有记录
                existingRecord.setIsRead(1);
                existingRecord.setReadTime(new Date());
                userNotificationReadService.updateById(existingRecord);
            } else {
                // 创建新的阅读记录
                UserNotificationRead readRecord = new UserNotificationRead();
                readRecord.setNotificationId(notificationId);
                readRecord.setUserId(userId);
                readRecord.setIsRead(1);
                readRecord.setReadTime(new Date());
                readRecord.setCreateTime(new Date());
                userNotificationReadService.save(readRecord);
            }
            
            return Result.success("标记成功");
            
        } catch (Exception e) {
            return Result.error("标记失败：" + e.getMessage());
        }
    }

    /**
     * 批量标记消息为已读
     */
    @PostMapping("/mark-read-batch")
    public Result<String> markAsReadBatch(@RequestParam List<Long> notificationIds, 
                                        @RequestParam Long userId) {
        try {
            for (Long notificationId : notificationIds) {
                // 检查是否已有阅读记录
                QueryWrapper<UserNotificationRead> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("notification_id", notificationId);
                queryWrapper.eq("user_id", userId);
                
                UserNotificationRead existingRecord = userNotificationReadService.getOne(queryWrapper);
                
                if (existingRecord != null) {
                    // 更新现有记录
                    existingRecord.setIsRead(1);
                    existingRecord.setReadTime(new Date());
                    userNotificationReadService.updateById(existingRecord);
                } else {
                    // 创建新的阅读记录
                    UserNotificationRead readRecord = new UserNotificationRead();
                    readRecord.setNotificationId(notificationId);
                    readRecord.setUserId(userId);
                    readRecord.setIsRead(1);
                    readRecord.setReadTime(new Date());
                    readRecord.setCreateTime(new Date());
                    userNotificationReadService.save(readRecord);
                }
            }
            
            return Result.success("批量标记成功");
            
        } catch (Exception e) {
            return Result.error("批量标记失败：" + e.getMessage());
        }
    }

    /**
     * 全部标记为已读
     */
    @PostMapping("/mark-all-read")
    public Result<String> markAllAsRead(@RequestParam Long userId) {
        try {
            // 获取用户可见的所有未读通知
            QueryWrapper<SystemNotification> notificationWrapper = new QueryWrapper<>();
            notificationWrapper.eq("status", "ACTIVE");
            notificationWrapper.and(wrapper -> wrapper
                .isNull("expire_time")
                .or().gt("expire_time", new Date())
            );
            notificationWrapper.and(wrapper -> wrapper
                .eq("target_type", "ALL")
                .or().eq("target_type", "USER").like("target_value", userId.toString())
                .or().eq("target_type", "ROLE")
            );
            
            List<SystemNotification> allNotifications = systemNotificationService.list(notificationWrapper);
            
            for (SystemNotification notification : allNotifications) {
                // 检查是否已有阅读记录
                QueryWrapper<UserNotificationRead> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("notification_id", notification.getId());
                queryWrapper.eq("user_id", userId);
                
                UserNotificationRead existingRecord = userNotificationReadService.getOne(queryWrapper);
                
                if (existingRecord != null) {
                    // 更新现有记录
                    existingRecord.setIsRead(1);
                    existingRecord.setReadTime(new Date());
                    userNotificationReadService.updateById(existingRecord);
                } else {
                    // 创建新的阅读记录
                    UserNotificationRead readRecord = new UserNotificationRead();
                    readRecord.setNotificationId(notification.getId());
                    readRecord.setUserId(userId);
                    readRecord.setIsRead(1);
                    readRecord.setReadTime(new Date());
                    readRecord.setCreateTime(new Date());
                    userNotificationReadService.save(readRecord);
                }
            }
            
            return Result.success("全部标记成功");
            
        } catch (Exception e) {
            return Result.error("全部标记失败：" + e.getMessage());
        }
    }

    /**
     * 获取通知详情
     */
    @GetMapping("/detail/{id}")
    public Result<SystemNotification> getNotificationDetail(@PathVariable Long id, 
                                                          @RequestParam Long userId) {
        try {
            SystemNotification notification = systemNotificationService.getById(id);
            
            if (notification == null) {
                return Result.notFound("通知不存在");
            }
            
            // 自动标记为已读
            markAsRead(id, userId);
            
            return Result.success("查询成功", notification);
            
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }
}




